package com.ruoyi.system.service.impl;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.sql.Timestamp;
import java.util.*;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.TiffUtil;
import com.ruoyi.system.domain.Productlist;
import com.ruoyi.system.domain.UserWorks;
import com.ruoyi.system.domain.dto.OrderDto;
import com.ruoyi.system.domain.vo.OrdersVo;
import com.ruoyi.system.mapper.ProductlistMapper;
import com.ruoyi.system.mapper.UserWorksMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.OrdersMapper;
import com.ruoyi.system.domain.Orders;
import com.ruoyi.system.service.IOrdersService;

import javax.imageio.ImageIO;

/**
 * 底图生成订单表Service业务层处理
 *
 * @author gs
 * @date 2025-04-30
 */
@Slf4j
@Service
public class OrdersServiceImpl implements IOrdersService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserWorksMapper userWorksMapper;

    @Autowired
    private ProductlistMapper productlistMapper;

    /**
     * 查询底图生成订单表
     *
     * @param orderId 底图生成订单表主键
     * @return 底图生成订单表
     */
    @Override
    public OrderDto selectOrdersByOrderId(String orderId) {
        OrderDto orderDto = ordersMapper.selectOrdersByOrderId(orderId);
        Productlist product = orderDto.getProduct();
        String productImage = product.getProductImage();
        String[] splitImg = productImage.split(",");
        product.setProductImage(splitImg[0]);
        return orderDto;
    }

    @Override
    public List<OrderDto> selectOrdersByStoreId(String storeId) {
        List<OrderDto> orderDtoList = ordersMapper.selectOrdersByStoreId(storeId);
        for (OrderDto item : orderDtoList) {
            Productlist product = item.getProduct();
            String productImage = product.getProductImage();
            String[] splitImg = productImage.split(",");
            product.setProductImage(splitImg[0]);
        }

        return orderDtoList;
    }

    @Override
    public Integer over(String orderId) {
        return ordersMapper.over(orderId);
    }

    /**
     * 查询底图生成订单表列表
     *
     * @param orders 底图生成订单表
     * @return 底图生成订单表
     */
    @Override
    public List<OrderDto> selectOrdersList(Orders orders) {
        OrdersVo ordersVo = new OrdersVo();
        BeanUtils.copyProperties(orders, ordersVo);

        if (orders.getOrderTime() != null) {
            Timestamp startTime = new Timestamp(orders.getOrderTime().getTime());
            startTime.setHours(0);
            startTime.setMinutes(0);
            startTime.setSeconds(0);

            Timestamp endTime = new Timestamp(orders.getOrderTime().getTime());
            endTime.setHours(23);
            endTime.setMinutes(59);
            endTime.setSeconds(59);
            ordersVo.setOrderTimeStart(startTime);
            ordersVo.setOrderTimeEnd(endTime);
        }

        if (orders.getCreateTime() != null) {
            Timestamp startTime = new Timestamp(orders.getCreateTime().getTime());
            startTime.setHours(0);
            startTime.setMinutes(0);
            startTime.setSeconds(0);

            Timestamp endTime = new Timestamp(orders.getCreateTime().getTime());
            endTime.setHours(23);
            endTime.setMinutes(59);
            endTime.setSeconds(59);

            ordersVo.setCreateTimeStart(startTime);
            ordersVo.setCreateTimeEnd(endTime);
        }

        List<OrderDto> orderDtoList = ordersMapper.selectOrdersList(ordersVo);

        for (OrderDto item : orderDtoList) {
            if (item.getProduct() == null) {
                continue;
            }
            Productlist product = item.getProduct();
            String productImage = product.getProductImage();
            String[] splitImg = productImage.split(",");
            product.setProductImage(splitImg[0]);
        }

        return orderDtoList;
    }

    /**
     * 新增底图生成订单表
     *
     * @param orders 底图生成订单表
     * @return 结果
     */
    @Override
    public int insertOrders(Orders orders) {
        orders.setCreateTime(DateUtils.getNowDate());
        if (orders.getOrderStatus().equals('1')) {
            Random random = new Random();
            int number = random.nextInt(90000000) + 10000000;
            orders.setPaymentNum(String.valueOf(number));
        }

        if (ordersMapper.selectOrdersByOrderId(String.valueOf(orders.getOrderId())) != null) {
            return ordersMapper.updateOrders(orders);
        } else return ordersMapper.insertOrders(orders);

    }


    /**
     * 修改底图生成订单表
     *
     * @param orders 底图生成订单表
     * @return 结果
     */
    @Override
    public int updateOrders(Orders orders) {
        if (Objects.equals(orders.getOrderStatus(), '1')) {
            if (Objects.isNull(orders.getPaymentNum())) {
                Random random = new Random();
                int number = random.nextInt(90000000) + 10000000;
                orders.setPaymentNum(String.valueOf(number));
            }
        } else {
            if (!Objects.isNull(orders.getPaymentNum())) {
                orders.setPaymentNum("");
            }
        }

        return ordersMapper.updateOrders(orders);
    }

    /**
     * 批量删除底图生成订单表
     *
     * @param orderIds 需要删除的底图生成订单表主键
     * @return 结果
     */
    @Override
    public int deleteOrdersByOrderIds(Long[] orderIds) {
        return ordersMapper.deleteOrdersByOrderIds(orderIds);
    }

    /**
     * 删除底图生成订单表信息
     *
     * @param orderId 底图生成订单表主键
     * @return 结果
     */
    @Override
    public int deleteOrdersByOrderId(Long orderId) {
        return ordersMapper.deleteOrdersByOrderId(orderId);
    }


    @Override
    public String payment(String orderId, String paymentNum) {
        try {

            log.info("---------------------------------------------------------");
            log.info("进入payment方法");
            Random random = new Random();
            int pickCode = random.nextInt(9000) + 1000;
            String url = null;
            UserWorks uw = userWorksMapper.selectUserWorksByHistoryOrder(orderId);
            String workImageUrl = uw.getWorkImage();

            OrderDto orderDto = ordersMapper.selectOrdersByOrderId(String.valueOf(orderId));

            Productlist product = productlistMapper.selectProductlistByProductId(Long.valueOf(orderDto.getUseImageName()));

            //图片转tiff格式上传保存，返回路径
            URL urlfile = new URL(workImageUrl);
            InputStream inStream = urlfile.openStream();
            BufferedImage bimg = ImageIO.read(inStream);
            //构建文件路径
            String fileName;
            if (product.getProductSizeType().equals("1")) {
                fileName = orderId + "_T1_S" + product.getProductId() + "_.tiff";
            } else {
                fileName = orderId + "_T2_S" + product.getProductId() + "_.tiff";
            }
            String filePath = makeFilePath() + fileName;
            File f = TiffUtil.writeImage(bimg, filePath);
            //更新路径
            String correctedPath = filePath.replaceFirst("^/project/", "");
            String paintwork = "https://lifein.asia/" + correctedPath;
//            String paintwork = "https://www.lifein.cc/" + correctedPath;
            log.info("图片路径 paintwork ：{}", paintwork);

            userWorksMapper.updatePaintworkByWorksId(paintwork, uw.getWorksId());
            ordersMapper.payment(orderId, pickCode, paymentNum,new Date());
            url = paintwork;
            return url;

        } catch (Exception e) {
            log.error("图片转tiff格式上传保存 --- {}", e.getMessage());
            log.error(e.toString());
        }
        return null;

    }

    public String makeFilePath() {
        String path = "/project/tiff/img/";
        //String path = "E:\\";

        Date currentDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);

        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);

        // 将 month 和 date 格式化为两位数
        String formattedMonth = String.format("%02d", month);
        String formattedDate = String.format("%02d", day);

        String filePath = path + String.valueOf(year) + formattedMonth + formattedDate + "/";
        return filePath;
    }

//    public static void main(String[] args) {
//     /*   String jpgPath = "path/to/image.jpg"; // 指定JPG文件路径
//        File jpgFile = new File(jpgPath); // 创建File对象
//
//        // 在这里，可以添加代码来检查文件是否存在
//        FileUploadUtils.upload()
//        try {
//            // 读取JPG文件
//            BufferedImage jpgImage = Imaging.getBufferedImage(jpgFile);
//            System.out.println("JPG文件读取成功！");
//        } catch (IOException e) {
//            e.printStackTrace();
//     */   }
//    }

    public static void main(String[] args) {
        // 使用 Path 类处理路径（需导入 java.nio.file.Paths;）
        String originalPath = "project/tiff/img/20250506/01cd3170-fdf7-451f-be34-2bb5901277a9.tiff";
        // 去掉 "project/" 前缀
        String correctedPath = originalPath.replaceFirst("^project/", "");
        // 或直接指定正确路径："tiff/img/20250506/01cd3170-fdf7-451f-be34-2bb59012    77a9.tiff"
        System.out.println(correctedPath);

    }

}
